package org.yzz.base.exception;

import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yzz.base.util.AjaxResult;

import java.util.List;

@RestControllerAdvice   // 在执行controller方法的前/后执行该代码
public class GlobalExceptionHandler {

    /**
     * 处理业务异常类的异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)	// 表示 controller 层的 catch(){} 异常在这里处理
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        return AjaxResult.error(e.getCode()+":"+e.getMessage(),e.getCode());    // BusinessException 捕捉到的异常 直接返给 controller
    }

    /**
     * jsr303 校验的异常捕捉，并处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuffer sb = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            sb.append(fieldError.getDefaultMessage());
            sb.append(",");
        }
        String message = sb.substring(0,sb.length()-1);
        return AjaxResult.error(message,ResponseCode.RESPONSE_CODE_4011.getCode());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.error("500:"+ResponseCode.RESPONSE_CODE_500.getMessage(),ResponseCode.RESPONSE_CODE_500.getCode());
    }
}